<template>
	<view style='padding:10px;'>
		<u--form labelPosition="left" labelWidth='100px'>
			<u-form-item label="头像">
				<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
					:maxCount="1"></u-upload>
			</u-form-item>
			<u-form-item label="昵称">
				<u--input v-model="form.nickname" border="none"></u--input>
			</u-form-item>
			<u-line></u-line>
			<u-form-item label="绑定手机">
				<u--input v-model="form.phone" border="none"></u--input>
				<u-button type='success' text='快速获取' slot="right" open-type="getPhoneNumber"
					@getphonenumber="getPhoneNumber"></u-button>
			</u-form-item>
			<u-line></u-line>
		</u--form>
		<view style='padding:20px'>
			<u-button type='primary' shape='circle' text='提交' @click='submit'></u-button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				loading: false,
				fileList1: [],
				form: {
					avatarUrl: '', // 头像URL
					nickname: '', // 昵称
					phone: '', // 手机号
					email: '' // 电子邮箱
				}
			}
		},
		onLoad() {
			this.request.get(`api/user`, {
				'@expands': "['profile']"
			}).then((res) => {
				console.log(res.data)
				if (res.data.profile.__metadata.nickname) {
					this.form.nickname = res.data.profile.__metadata.nickname
				}
				if (res.data.profile.__metadata.avatarUrl) {
					this.form.avatarUrl = res.data.profile.__metadata.avatarUrl
					this.fileList1.push(res.data.profile.__metadata.avatarUrl)
				}
				if (res.data.profile.__metadata.phone) {
					this.form.phone = res.data.profile.__metadata.phone
				}
				if (res.data.email) {
					this.form.email = res.data.email
				}
			})
		},
		methods: {
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1);
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file);
				let fileListLen = this[`fileList${event.name}`].length;
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: "uploading",
						message: "上传中",
					});
				});
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url);
					let item = this[`fileList${event.name}`][fileListLen];
					this[`fileList${event.name}`].splice(
						fileListLen,
						1,
						Object.assign(item, {
							status: "success",
							message: "",
							url: result,
						})
					);
					fileListLen++;
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: `${getApp().globalData.apiBase}upload?storage=qiniu`, // 仅为示例，非真实的接口地址
						filePath: url,
						name: "file",
						formData: {
							user: "test",
						},
						success: (res) => {
							let uploadData = JSON.parse(res.data)
							this.form.avatarUrl = uploadData.data[0]
							uni.hideLoading()
							setTimeout(() => {
								resolve(res.data.data);
							}, 1000);
						},
					});
				});
			},
			submit(){
				this.request.put(`api/user-profile`, this.form).then((res) => {
					uni.showModal({
						title: '',
						content: '提交成功！',
						showCancel: false,
						success: () => {
							uni.switchTab({
								url: '/pages/mine/index'
							})
						}
					})
				})
			},
			getPhoneNumber(e) {
				let _this = this
				if (typeof(e.detail.iv) == 'undefined') {
					uni.showToast({
						title: '获取失败,请手动输入',
						icon: 'none'
					})
					return
				} else {
					uni.showLoading()
					uni.login({
						provider: "weixin",
						success: function(res) {
							let data = {
								code: res.code
							}
							_this.request.get("wechat/mini/login", data).then((res) => {
								if (res.data.data.session_key) {
									let data = {
										sessionKey: res.data.data.session_key,
										iv: e.detail.iv,
										encryptedData: e.detail.encryptedData,
									}
									_this.request.post(`wechat/decrypt-data`, data).then((res) => {
										_this.form.phone = res.data.phoneNumber
										//更新手机号码
										_this.request.put(`api/user-profile`, {
											phone: res.data.phoneNumber
										}).then((res) => {
											console.log(res)
										})
										uni.hideLoading()
									})
								} else {
									uni.hideLoading()
									uni.showToast({
										title: '获取手机号码失败！',
										icon: 'none'
									})
								}
							})
						},
					});
				}
			},
		}
	}
</script>

<style lang="scss" scoped>

</style>